<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection;

class AutoPlusApple extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cc:auto-plus-apple';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {


         User::query()
            ->where('grade','vip')
            ->where('vip_expired_at','>',Carbon::now())
            ->chunk(50, function (Collection $users) {

            if ($users->isEmpty()) return false;

            /**
             * @var User $user
             */
        
            foreach ($users as $user) {
                if($user->is_stop){
                  continue;
                }

                if($user->rewarded_at > 0){
                    $time = time()-intval($user->rewarded_at);
                }else{

                   continue;
                }

                $ownApples = $user->ownOneSeconds()->multipliedBy($time);
                account_apples($user)->plusOwnTreeProduceApples($ownApples);
                $res = $user->myDownOneChildren()->get();
                foreach($res as $v){
                   $v->dividendChildApples();
                }
                if($res && $user->oneLevelTeamSeconds()->isGreaterThan(0)){
                    $ownApples = $user->oneLevelTeamSeconds()->multipliedBy($time);
                    account_apples($user)->plusTreeProduceApples($ownApples,1);

                }

                for($i=2;$i<=2;$i++){

                    $hasValidUser = $user->myTeam()->where('relation_users.team_level',$i)->exists();
                   
                    if($hasValidUser && $user->allowedPart($i)){
                        if($user->moreLevelTeamSeconds($i)->isGreaterThan(0)){

                             account_apples($user)->plusTreeProduceApples($user->moreLevelTeamSeconds($i)->multipliedBy($time),$i);
                        }

                    }else{

                        break;
                    }

                }

                $user->update(['rewarded_at'=>time()]);

            }   

            return true;

        });
    }
}
